package com.cskaoyan.service;

import com.cskaoyan.bean.DataBean;
import com.cskaoyan.bean.admin.Admin;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class AuthenticateServiceImpl implements AuthenticateService {

    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    RoleMapper roleMapper;

    @Override
    public DataBean info() {
        DataBean dataBean = new DataBean();
        Subject subject = SecurityUtils.getSubject();
        Admin principal = (Admin) subject.getPrincipal();
        if (principal == null)
            return dataBean;
        String avatar = principal.getAvatar();
        String username = principal.getUsername();
        Integer[] roleIds =  principal.getRoleIds();
        List<String> perms = new ArrayList<>();
        List<String> temp = new ArrayList<>();
        ArrayList<String> roles = new ArrayList<>();

        for (Integer roleId : roleIds) {
            int result = permissionMapper.selectTongPei(roleId);
            if (result == 1) {
                temp.clear();
                temp.add("*");
                break;
            }
            temp.addAll(permissionMapper.selectApiByRoleId(roleId));
        }
        for (Integer roleId : roleIds) {
            String roleName = roleMapper.selectNameById(roleId);
            roles.add(roleName);
        }
        for (String s : temp) {
            if (!perms.contains(s)) {
                perms.add(s);
            }
        }
        if (perms.size() == 89) {
            perms.clear();
            perms.add("*");
        }
        dataBean.setPerms(perms);
        dataBean.setAvatar(avatar);
        dataBean.setName(username);
        dataBean.setRoles(roles);

        return dataBean;
    }
}
